<template>
  <div class="app-container">
    <!-- <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch" label-width="88px">
      <el-form-item label="供应商名称" prop="name">
        <el-input
          v-model="queryParams.name"
          placeholder="请输入供应商名称"
          clearable
          style="width: 240px"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form> -->

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd(1)"
          v-hasPermi="['system:faDeviceTask:add']"
        >新增</el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="list">
      <el-table-column label="升级任务id" align="center" prop="id" />
      <el-table-column label="升级状态" align="center" prop="supplierName" >
        <template slot-scope="{row}">
          {{row.finish === row.total && row.total > 0 ? '已完成' : '未完成'}}
        </template>
      </el-table-column>
      <el-table-column label="总计" align="center" prop="total" />
      <el-table-column label="已完成" align="center" prop="finish" />
      <el-table-column label="创建时间" align="center" prop="createTime" />
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="{row}">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(row)"
            v-hasPermi="['system:faDeviceTask:edit']"
          ></el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(row)"
            v-hasPermi="['system:faDeviceTask:remove']"
          ></el-button>
          <el-button
            type="text"
            icon="el-icon-folder"
            size="mini"
            @click="handleDetail(row)"
            v-hasPermi="['system:faDeviceTask:taskInfoList']"
          ></el-button>
          <el-button
            type="text"
            icon="el-icon-plus"
            size="mini"
            @click="handleAdd(2,row)"
            v-hasPermi="['system:faDeviceTask:addTaskInfo']"
          ></el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改参数配置对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="60%" append-to-body>
      <el-form ref="form" :model="form" :rules="rules" label-width="120px">
        <div v-if="formType == 2">
          <el-form-item label="类型选择" prop="type">
            <el-select v-model="form.type" @change="typeChange" placeholder="请选择类型">
              <el-option
                v-for="item in dict.type.task_type1"
                :key="item.value"
                :label="item.label"
                :value="Number(item.value)">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="内容选择" prop="extPara" v-if="form.type > 0">
            <el-select v-model="form.extPara" multiple placeholder="请选择内容选择">
              <el-option
                v-for="item in contList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </div>
        <div v-else>
          <el-form-item label="项目" prop="projectId">
            <el-select v-model="form.projectId" @change="projectChange" :disabled="getDiasble()" placeholder="请选择项目">
              <el-option
                v-for="item in projectList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="固件" prop="firmId">
            <el-select v-model="form.firmId" placeholder="请选择固件" :disabled="getDiasble()">
              <el-option
                v-for="item in firmwareList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="开始时间" prop="startTime">
            <el-time-picker
              v-model="form.startTime"
              value-format="HH:mm:ss"
              :picker-options="{
                selectableRange: '00:00:00 - 23:59:59'
              }"
              placeholder="开始时间">
            </el-time-picker>
          </el-form-item>
          <el-form-item label="结束时间" prop="endTime">
            <el-time-picker
              v-model="form.endTime"
              value-format="HH:mm:ss"
              :picker-options="{
                selectableRange: '00:00:00 - 23:59:59'
              }"
              placeholder="结束时间">
            </el-time-picker>
          </el-form-item>
          <el-form-item label="是否同版本升级" prop="sameVersionUpdate">
            <el-radio-group v-model="form.sameVersionUpdate" :disabled="getDiasble()">
              <el-radio v-for="(item,index) in dict.type.comm_isyesno" :key="index" :label="Number(item.value)">{{item.label}}</el-radio>
            </el-radio-group>
          </el-form-item>
          <el-form-item label="最大数量" prop="maxNum" >
            <el-input-number v-model="form.maxNum" :step="1" :min="0" step-strictly :disabled="getDiasble()"></el-input-number>
          </el-form-item>
          <el-form-item label="类型选择" prop="type">
            <el-select v-model="form.type" @change="typeChange" placeholder="请选择类型" :disabled="getDiasble()">
              <el-option
                v-for="item in dict.type.task_type"
                :key="item.value"
                :label="item.label"
                :value="Number(item.value)">
              </el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="内容选择" prop="extPara" v-if="form.type > 0">
            <el-select v-model="form.extPara" multiple placeholder="请选择内容选择" :disabled="getDiasble()">
              <el-option
                v-for="item in contList"
                :key="item.id"
                :label="item.name"
                :value="item.id">
              </el-option>
            </el-select>
          </el-form-item>
        </div>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>

    <!-- 对话框 -->
    <el-dialog :title="rwTitle" :visible.sync="rwOpen" width="70%" append-to-body>
      <el-table v-loading="rwLoading" :data="rwList">
        <el-table-column label="车位编号" align="center" prop="placenum" />
        <el-table-column label="设备sn" align="center" prop="deviceSn" />
        <el-table-column label="升级状态" align="center" prop="firmType" >
          <template slot-scope="{row}">
            {{ row.status == 1 ? '已完成' : '未完成' }}
          </template>
        </el-table-column>
        <el-table-column label="总计" align="center" prop="totalSize" />
        <el-table-column label="已完成" align="center" prop="finishSize" />
        <el-table-column label="创建时间" align="center" prop="createTime" />
        <el-table-column label="更新时间" align="center" prop="updateTime" />
        <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
          <template slot-scope="{row}">
            <el-button
              size="mini"
              type="text"
              icon="el-icon-delete"
              @click="rwHandleDelete(row)"
              v-hasPermi="['system:faDeviceTask:removeTaskInfo']"
            >删除</el-button>
          </template>
        </el-table-column>
      </el-table>

      <pagination
        v-show="rwTotal>0"
        :total="rwTotal"
        :page.sync="rwQueryParams.pageNum"
        :limit.sync="rwQueryParams.pageSize"
        @pagination="faDeviceTaskInfoList"
      />

      <div slot="footer" class="dialog-footer">
        <el-button @click="rwOpen = false">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import { getfaDeviceTaskList, addTaskInfo, addFaDeviceTask, updateFaDeviceTask,delFaDeviceTask,
  faDeviceTaskInfoList,faDeviceTaskInfoRemove,} from "@/api/parking/task";
  import { listAllFaParkProject, } from "@/api/config/projectPushManage";
  import { getfaParkParklotList,} from "@/api/parking/parkingInfo";
  import {getList} from "@/api/parking/devices";
  import { getallfaDeviceFirmList,} from "@/api/parking/firmware";
  import { getAllSwVersion,} from "@/api/parking/devices";
export default {
  name: "Task",
  dicts: ['comm_isyesno','task_type','task_type1'],
  data() {
    return {
      // 遮罩层
      loading: true,
      rwLoading: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      rwTotal: 0,
      // 字典表格数据
      list: [],
      rwList: [],
      // 弹出层标题
      title: "",
      rwTitle: "",
      // 是否显示弹出层
      open: false,
      rwOpen: false,
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      rwQueryParams: {
        pageNum: 1,
        pageSize: 10,
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        maxNum: [{ required: true, message: "最大数量不能为空", trigger: "blur" }],
        projectId: [{ required: true, message: "项目不能为空", trigger: "change" }],
        firmId: [{ required: true, message: "固件不能为空", trigger: "change" }],
        startTime: [{ required: true, message: "开始时间不能为空", trigger: "change" }],
        endTime: [{ required: true, message: "结束时间不能为空", trigger: "change" }],
        sameVersionUpdate: [{ required: true, message: "是否同版本升级不能为空", trigger: "change" }],
        type: [{ required: true, message: "类型不能为空", trigger: "change" }],
        extPara: [{ required: true, message: "内容选择不能为空", trigger: "change" }],
      },
      projectList:[],//项目列表
      contList:[],//内容数据
      parkList:[],//停车场数据
      deviceList:[],//设备数据
      firmwareList:[],//固件列表
      banbenList:[],//固件版本列表
      formType:'',
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getDiasble(){
      return this.formType == 3 ? true : false
    },
    async getAllSwVersion(){//查询固件版本列表
      let res = await getAllSwVersion()
      let data = res.data || []
      this.contList = data.map(item=>{
        return {...item,name:item,id:item}
      })
    },
    async getallfaDeviceFirmList(){//查询所有设备固件列表
      let res = await getallfaDeviceFirmList()
      let data = res.data || []
      this.firmwareList = data
    },
    projectChange(e){//项目选择
      this.typeChange()
    },
    async getfaParkParklotList(projectId){//停车长列表
      let res = await getfaParkParklotList({pageNum: 1,pageSize: 100000,projectId})
      let rows = res.rows || []
      this.contList = rows.map(item=>{
        return {...item,id:item.pkParklotId}
      })
    },
    async getdevices(projectId){//设备类表
      let res = await getList({pageNum: 1,pageSize: 100000,deviceInventoryStatus:1,projectId})
      let rows = res.rows || []
      this.contList = rows.map(item=>{
        return {...item,name:item.deviceSn,id:item.deviceSn}
      })
    },
    async listAllFaParkProject(){//项目数据
      let res = await listAllFaParkProject()
      let data = res.data || []
      this.projectList = data
    },
    typeChange(e){//类型选择
      let form = {...this.form}
      form.extPara = []
      this.form = {...form}
      if(e == 1) {
        if(this.form.projectId) this.getdevices(this.form.projectId)
      }
      if(e == 2) {
        if(this.form.projectId) this.getfaParkParklotList(this.form.projectId)
      }
      if(e == 3) {
        if(this.form.projectId) this.getAllSwVersion(this.form.projectId)
      }
    },
    /** 查询列表 */
    getList() {
      this.loading = true;
      getfaDeviceTaskList(this.queryParams).then(response => {
          this.list = response.rows || [];
          this.total = response.total || 0;
          this.loading = false;
        }
      );
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {sameVersionUpdate:0,type:0,};
      this.resetForm("form");
      this.listAllFaParkProject()
      this.getallfaDeviceFirmList()
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.dateRange = [];
      this.resetForm("queryForm");
      this.handleQuery();
    },
    async faDeviceTaskInfoList(){//任务详情列表
      this.rwLoading = true
      let res = await faDeviceTaskInfoList(this.rwQueryParams)
      let rows = res.rows || []
      this.rwTotal = res.total
      this.rwList = rows
      this.rwLoading = false
    },
    handleDetail(row) {//任务详情列表
      this.rwOpen = true;
      this.rwTitle = "任务详情列表";
      this.rwQueryParams.taskId = row.id
      this.rwQueryParams.pageNum = 1
      this.faDeviceTaskInfoList()
    },
    /** 新增按钮操作 */
    handleAdd(type,row) {
      this.formType = type
      this.reset();
      this.open = true;
      this.title = type == 2 ? "添加任务详情" : "添加任务管理";
      if(type == 2){
        this.form = {type:1,projectId:row.projectId};
        this.form.taskId = row.id
        if(this.form.type && row.projectId) this.typeChange(this.form.type)
      }
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.formType = 3
      this.reset();
      let extPara = row.extPara || ''
      this.form = {...row,extPara:extPara ? extPara.split(',') : []};
      this.open = true;
      this.title = "修改任务管理";
      if(this.form.type && this.form.projectId) this.typeChange(this.form.type)
    },
    /** 提交按钮 */
    submitForm: function() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          let form = {...this.form}
          if(this.formType == 2) {
            form.extPara = form.extPara.toString()
            addTaskInfo(form).then(response => {
              this.$modal.msgSuccess("新增成功");
              this.open = false;
              this.handleDetail({id:this.form.taskId});
            });
          }else{
            if(form.type > 0) form.extPara = form.extPara.toString()
            if (this.form.id != undefined) {
              updateFaDeviceTask(form).then(response => {
                this.$modal.msgSuccess("修改成功");
                this.open = false;
                this.getList();
              });
            } else {
              addFaDeviceTask(form).then(response => {
                this.$modal.msgSuccess("新增成功");
                this.open = false;
                this.getList();
              });
            }
          }
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const dictIds = row.id
      this.$modal.confirm('是否确认删除该数据项？').then(function() {
        return delFaDeviceTask(dictIds);
      }).then(() => {
        this.getList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
    /** 任务详情删除按钮操作 */
    rwHandleDelete(row) {
      const dictIds = row.id
      this.$modal.confirm('是否确认删除该数据项？').then(function() {
        return faDeviceTaskInfoRemove(dictIds);
      }).then(() => {
        this.faDeviceTaskInfoList();
        this.$modal.msgSuccess("删除成功");
      }).catch(() => {});
    },
  }
};
</script>
